//
//  WebViewController.m
//  JPWords
//
//  Created by 梁淑婷 on 2024/5/26.
//

#import "WebViewController.h"
#import <WebKit/WebKit.h>

@interface WebViewController ()<WKUIDelegate,WKNavigationDelegate>

@property(nonatomic,strong)WKWebView *webView;
@property(nonatomic,strong)UIProgressView *progressView;

@end

@implementation WebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.customNavigationBar.backgroundColor = [UIColor whiteColor];
    [self.customNavigationBar setTitle:self.titleStr];
    
    self.webView.UIDelegate = self;
    self.webView.navigationDelegate = self;
    [self.view addSubview:self.webView];
    [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(kYM_NAVIGATIONBAR_HEIGHT);
        make.left.right.bottom.mas_equalTo(@0);
    }];
    
    //进度条初始化
    self.progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0,kYM_NAVIGATIONBAR_HEIGHT,self.currentAvailableWidth,2)];
    self.progressView.backgroundColor = [UIColor whiteColor];
    self.progressView.progressTintColor = KThemeColor;
    //设置进度条的高度，下面这句代码表示进度条的宽度变为原来的1倍，高度变为原来的1.5倍.
    self.progressView.transform = CGAffineTransformMakeScale(1.0f,1.5f);
    [self.view addSubview:self.progressView];
    
    
    NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:self.webUrlString]];
    [self.webView loadRequest:req];
        
    
}

#pragma mark - 屏幕宽度改变
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
    if(isIPAD){
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
           // 获取当前可用宽度并更新布局
           self.currentAvailableWidth = [DeviceUtils currentAvailableWidth];
           self.currentAvailableHeight = [DeviceUtils currentAvailableHeight];
           self.customNavigationBar.frame = CGRectMake(0, 0, self.currentAvailableWidth,kYM_NAVIGATIONBAR_HEIGHT);
            [self.webView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.left.right.bottom.mas_equalTo(@0);
            }];
            self.progressView.frame = CGRectMake(0,kYM_NAVIGATIONBAR_HEIGHT,self.currentAvailableWidth,2);
        });
    }
}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self changeAllowsBackForward];
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.webView.allowsBackForwardNavigationGestures = NO;
    [self popGestureOpen];
}


-(WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures{
    if(navigationAction.targetFrame == nil||!navigationAction.targetFrame.isMainFrame){
        if(!navigationAction.targetFrame.isMainFrame){
            if (@available(iOS 10.0, *)) {
                [[UIApplication sharedApplication] openURL:navigationAction.request.URL options:@{} completionHandler:nil];
            }
        }else{
            [webView loadRequest:navigationAction.request];
        }
    }
    return nil;
}


//开始加载
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    NSLog(@"开始加载网页");
    //开始加载网页时展示出progressView
    self.progressView.hidden = NO;
    //开始加载网页的时候将progressView的Height恢复为1.5倍
    self.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.5f);
    //防止progressView被网页挡住
    [self.view bringSubviewToFront:self.progressView];
}


//页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation{
    //加载完成后隐藏progressView
    self.progressView.hidden = YES;
    [self changeAllowsBackForward];
}

-(void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error{
    //加载失败同样需要隐藏progressView
    self.progressView.hidden = YES;
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        self.progressView.progress = self.webView.estimatedProgress;
        if (self.progressView.progress == 1) {
            /*
             *添加一个简单的动画，将progressView的Height变为1.4倍，在开始加载网页的代理中会恢复为1.5倍
             *动画时长0.25s，延时0.3s后开始动画
             *动画结束后将progressView隐藏
             */
            __weak typeof (self)weakSelf = self;
            [UIView animateWithDuration:0.25f delay:0.3f options:UIViewAnimationOptionCurveEaseOut animations:^{
                weakSelf.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.4f);
            } completion:^(BOOL finished) {
                weakSelf.progressView.hidden = YES;

            }];
        }
    }else{
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

- (void)defaultBackSet{
    [self.customNavigationBar setLeftItemWithIcon:[UIImage imageNamed:@"nav_back_logo"]];
    [self.customNavigationBar.leftButton addTarget:self action:@selector(__backButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
}

-(void)__backButtonClicked:(UIButton*)btn{
    if ([self.webView canGoBack]) {
        [self.webView goBack];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark - 修改滑动返回是系统控制还是wkwebview
-(void)changeAllowsBackForward{
    if (self.webView.canGoBack == YES) {
        if(self.webView.allowsBackForwardNavigationGestures == NO){
            [self popGestureClose];
            self.webView.allowsBackForwardNavigationGestures = YES;
        }
    }else{
        if(self.webView.allowsBackForwardNavigationGestures == YES){
            [self popGestureOpen];
            self.webView.allowsBackForwardNavigationGestures = NO;
        }
    }
}

- (WKWebView *)webView{
    if (!_webView) {
        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc]init];
        _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, kYM_NAVIGATIONBAR_HEIGHT, self.currentAvailableWidth, self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT) configuration:config];
        _webView.translatesAutoresizingMaskIntoConstraints = NO;
        _webView.backgroundColor = [UIColor whiteColor];
        [_webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    }
    return _webView;
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    if(self.webView){
        [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
        self.webView = nil;
    }
    
}

@end
